package rs.crawlerUtil;

import rs.Conf;
import rs.Crawler;
import rs.util.Log;
import rs.util.StringUtil;
import rs.util.TimeUtil;



public class ProxyChecker {
	
	public static String checkUrl = Conf.PROXY_CHECK_URL;
	
	public static String checkStr = Conf.PROXY_CHECK_STRING;
	
	
	
	public static int checkProxy(HttpProxy host){
		long startTime = TimeUtil.now();
		String url = checkUrl + "?t=" + startTime;
		try{
			Crawler c = new Crawler();
			String html = c.work(url, host, null).html();
			String content = StringUtil.find(html, checkStr);
			//System.out.println("Content @" + url + "\n" + content);
			int costTime = (int)(TimeUtil.now() - startTime);
			if(content == null){
				Log.info("Proxy: check failed " + host.getHostName() + " because no content got");
				return -1;
			} else {
				if(content.indexOf(checkStr) == -1){
					Log.info("Proxy: check failed " + host.getHostName() + " because wrong content got");
					return -1;
				}
			}
			return costTime;
		} catch (Throwable e) {
			Log.info("Proxy: check failed " + host.getHostName() + " because " + e.getMessage());
			return -1;
		}
	}
	
	public static int avgCheckProxy(HttpProxy host, int times){
		try{
			int total = 0, tmp;
			for(int i=0; i < times; ++i){
				tmp = checkProxy(host);
				if(tmp < 0){return tmp;}
				total += tmp;
			}
			return total / times;
		} catch (Exception e) {
			return -1;
		}
	}
	
	public static int avgCheckProxy(HttpProxy host){
		return avgCheckProxy(host, 2);
	}
	
	public static void main(String[] args) {
		String p = "125.77.194.103:80";
		//String p = "127.0.0.1:1080";
		HttpProxy proxy = ProxyMgr.genProxy(p);
//		HttpProxy proxy = new HttpProxy("68.38.247.234",8085,"http");
		System.out.println(avgCheckProxy(proxy,1));
	}
}
